package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	v1pb "quipus/proto/gen/api/v1"
	cpb "quipus/proto/gen/common"

	"github.com/spf13/cobra"
)

var (
	appId     string
	secretKey string
	idpType   string
	title     string
)

func init() {
	createCmd.PersistentFlags().StringVarP(&appId, "appid", "a", "", "the appid for wechat")
	createCmd.PersistentFlags().StringVarP(&secretKey, "secretkey", "s", "", "the secretkey for wechat")
	createCmd.PersistentFlags().StringVarP(&idpType, "idp-type", "i", "", "the idp type for wechat")
	createCmd.PersistentFlags().StringVarP(&title, "title", "t", "", "the title for wechat")

	idpCmd.AddCommand(createCmd)
}

var createCmd = &cobra.Command{
	Use:   "create",
	Short: "Run the cmd to create idp",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewIdentityProviderServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		ic := &v1pb.IdentityProviderConfig{}
		ic.Config = &v1pb.IdentityProviderConfig_WeixinConfig{WeixinConfig: &v1pb.WeixinConfig{SecretKey: secretKey, AppId: appId}}
		in := &v1pb.CreateIdentityProviderRequest{Title: title, Type: cpb.IdpType_weixin, Config: ic}

		rsp, err := qclient.CreateIdentityProvider(ctxWithToken, in)
		if err != nil {
			return err
		}
		fmt.Print(rsp)
		return nil
	},
}
